<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 5.1</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="5.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="5.2.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P1">Part I. The Language</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#5">Chapter 5. Functions</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><h2>5.1 &ndash; Multiple Results</h2>

<p>An unconventional, but quite convenient feature of Lua
is that functions may return multiple results.
Several predefined functions in Lua return multiple values.
An example is the <code>string.find</code> function,
which locates a pattern in a string.
It returns two indices:
the index of the character where the pattern match starts
and the one where it ends (or <B>nil</B> if it cannot find the pattern).
A multiple assignment allows the program to get both results:
<pre>
    s, e = string.find("hello Lua users", "Lua")
    
    print(s, e)   -->  7      9
</pre>

<p>Functions written in Lua also can return multiple results,
by listing them all after the <b>return</b> keyword.
For instance, a function to find the maximum element in an array
can return both the maximum value and its location:
<pre>
    function maximum (a)
      local mi = 1          -- maximum index
      local m = a[mi]       -- maximum value
      for i,val in ipairs(a) do
        if val > m then
          mi = i
          m = val
        end
      end
      return m, mi
    end
    
    print(maximum({8,10,23,12,5}))     --> 23   3
</pre>

<p>Lua always adjusts the number of results from a function to
the circumstances of the call.
When we call a function as a statement,
Lua discards all of its results.
When we use a call as an expression,
Lua keeps only the first result.
We get all results
only when the call is the last (or the only) expression in
a list of expressions.
These lists appear in four constructions in Lua:
multiple assignment, arguments to function calls,
table constructors, and <b>return</b> statements.
To illustrate all these uses,
we will assume the following definitions
for the next examples:
<pre>
    function foo0 () end                  -- returns no results
    function foo1 () return 'a' end       -- returns 1 result
    function foo2 () return 'a','b' end   -- returns 2 results
</pre>

<p>In a multiple assignment, a function call as the last (or only)
expression produces as many results as needed to match the
variables:
<pre>
    x,y = foo2()        -- x='a', y='b'
    x = foo2()          -- x='a', 'b' is discarded
    x,y,z = 10,foo2()   -- x=10, y='a', z='b'
</pre>
If a function has no results, or not as many results as we need,
Lua produces <B>nil</B>s:
<pre>
    x,y = foo0()      -- x=nil, y=nil
    x,y = foo1()      -- x='a', y=nil
    x,y,z = foo2()    -- x='a', y='b', z=nil
</pre>
A function call that is not the last element in the list
always produces one result:
<pre>
    x,y = foo2(), 20      -- x='a', y=20
    x,y = foo0(), 20, 30  -- x='nil', y=20, 30 is discarded
</pre>

<p>When a function call is the last (or the only) argument to another call,
all results from the first call go as arguments.
We have seen examples of this construction already,
with <code>print</code>:
<pre>
    print(foo0())          -->
    print(foo1())          -->  a
    print(foo2())          -->  a   b
    print(foo2(), 1)       -->  a   1
    print(foo2() .. "x")   -->  ax         (see below)
</pre>
When the call to <code>foo2</code> appears inside an expression,
Lua adjusts the number of results to one;
so, in the last line, only the <code>"a"</code> is used in the concatenation.

<p>The <code>print</code> function
may receive a variable number of arguments.
(In the next section we will see how to write functions with
variable number of arguments.)
If we write <code>f(g())</code>
and <code>f</code> has a fixed number of arguments,
Lua adjusts the number of results of <code>g</code> to the number
of parameters of <code>f</code>,
as we saw previously.

<p>A constructor also collects all results from a call,
without any adjustments:
<pre>
    a = {foo0()}         -- a = {}  (an empty table)
    a = {foo1()}         -- a = {'a'}
    a = {foo2()}         -- a = {'a', 'b'}
</pre>
As always, this behavior happens only when the call is
the last in the list;
otherwise, any call produces exactly one result:
<pre>
    a = {foo0(), foo2(), 4}   -- a[1] = nil, a[2] = 'a', a[3] = 4
</pre>

<p>Finally, a statement like <code>return f()</code> returns all values
returned by <code>f</code>:
<pre>
    function foo (i)
      if i == 0 then return foo0()
      elseif i == 1 then return foo1()
      elseif i == 2 then return foo2()
      end
    end
    
    print(foo(1))     --> a
    print(foo(2))     --> a  b
    print(foo(0))     -- (no results)
    print(foo(3))     -- (no results)
</pre>

<p>You can force a call to return exactly one result by
enclosing it in an extra pair of parentheses:
<pre>
    print((foo0()))        --> nil
    print((foo1()))        --> a
    print((foo2()))        --> a
</pre>
Beware that a <b>return</b> statement does not need parentheses around
the returned value,
so any pair of parentheses placed there counts as an extra pair.
That is,
a statement like <code>return (f())</code> always returns one single value,
no matter how many values <code>f</code> returns.
Maybe this is what you want, maybe not.

<p>A special function with multiple returns is <code>unpack</code>.
It receives an array
and returns as results all elements from the array,
starting from index 1:
<pre>
    print(unpack{10,20,30})    --> 10   20   30
    a,b = unpack{10,20,30}     -- a=10, b=20, 30 is discarded
</pre>

<p>An important use for <code>unpack</code> is in a <em>generic call</em> mechanism.
A generic call mechanism allows you to call any function,
with any arguments, dynamically.
In ANSI C, for instance, there is no way to do that.
You can declare a function
that receives a variable number of arguments (with <code>stdarg.h</code>)
and you can call a variable function, using pointers to functions.
However, you cannot call a function with a variable number of arguments:
Each call you write in C has a fixed number of arguments
and each argument has a fixed type.
In Lua, if you want to call a variable function <code>f</code>
with variable arguments in an array <code>a</code>,
you simply write
<pre>
    f(unpack(a))
</pre>
The call to <code>unpack</code> returns all values in <code>a</code>,
which become the arguments to <code>f</code>.
For instance, if we execute
<pre>
    f = string.find
    a = {"hello", "ll"}
</pre>
then the call <code>f(unpack(a))</code> returns 3 and 4,
exactly the same as the static call <code>string.find("hello", "ll")</code>.

<p>Although the predefined <code>unpack</code> is written in C,
we could write it also in Lua,
using recursion:
<pre>
    function unpack (t, i)
      i = i or 1
      if t[i] ~= nil then
        return t[i], unpack(t, i + 1)
      end
    end
</pre>
The first time we call it,
with a single argument, <code>i</code> gets 1.
Then the function returns <code>t[1]</code>
followed by all results from <code>unpack(t, 2)</code>,
which in turn returns <code>t[2]</code>
followed by all results from <code>unpack(t, 3)</code>,
and so on, until the last non-nil element.

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="5.2.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

